package com.wswy.wzcx.ui.user

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.text.TextUtils
import com.che.libcommon.utils.RxBus
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.UserMode
import com.wswy.wzcx.model.resp.CaptchaData
import com.wswy.wzcx.model.resp.WXLoginResp
import com.wswy.wzcx.module.GlobalConfigManager
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.ScTimes
import com.wswy.wzcx.module.base.ApiCallback.Companion.toastErrorMsg
import com.wswy.wzcx.module.base.BaseViewModel
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.module.base.SingleLiveData
import com.wswy.wzcx.module.base.onResult
import com.wswy.wzcx.module.validator.ValidatorResult
import com.wswy.wzcx.utils.SecurityCheckerUtils
import com.wswy.wzcx.utils.ShareHelper
import io.reactivex.observers.ResourceObserver

class LoginHolderViewModel : BaseViewModel() {

    companion object {
        const val CLICK_LOGIN = 1
        const val CLICK_REG = 2
        const val CLICK_WECHAT_LOGIN = 3
        const val CLICK_REG_NEXT_VERIFY = 4
        const val CLICK_SMS_CODE_NEXT_STEP = 5
        const val CLICK_FORGET_PWD = 6

        const val CLICK_WX_BIND_SUCCESS = 7

        const val CLICK_ONE_KEY_LOGIN = 8

        const val TYPE_LOGIN = 1
        const val TYPE_REG = 2
        const val TYPE_FORGET_PWD = 3
        const val TYPE_WECHAT_BIND = 4

    }

    private val smsCodeLiveData = MutableLiveData<Resource<Boolean?>>()

    private val userLoginLiveData = MutableLiveData<Resource<UserMode?>>()

    private val clickEventLiveData = MutableLiveData<Int>()

    private val userModeLiveData = MutableLiveData<UserMode?>()

    private val wxLoginLiveData = MutableLiveData<WXLoginResp?>()

    private val getCaptchaLiveData = MutableLiveData<Resource<CaptchaData?>>()

    private var wxLoginReqSign:String?=null

    val oneKeyLogin = !TextUtils.isEmpty(BuildConfig.SHANYAN_APPID) && GlobalConfigManager.getInstance().sysConf.isEnableSYOneKeyLogin()

    val stepState = StepState()

    fun clickEvent(event:Int){

        when(event){
            CLICK_LOGIN -> {
                stepState.type = TYPE_LOGIN
            }

            CLICK_REG -> {
                stepState.type = TYPE_REG
            }

            CLICK_FORGET_PWD -> {
                stepState.type = TYPE_FORGET_PWD
            }
            CLICK_WECHAT_LOGIN -> {
                stepState.type = TYPE_WECHAT_BIND
            }

        }

        clickEventLiveData.postValue(event)

    }

    override fun onCreate() {
        super.onCreate()

    }

    fun watchWXLogin(){
        val wxLogin = object : ResourceObserver<WXLoginResp>() {
            override fun onNext(login: WXLoginResp) {
                //验证微信登录
                if (login.errCode == 0 && TextUtils.equals(wxLoginReqSign,login.state)){
                    wxLoginLiveData.postValue(login)
                }else{
                    ToastUtils.showText(login.errorMsg)
                }
            }

            override fun onError(e: Throwable) {
                e.printStackTrace()
            }

            override fun onComplete() {
            }
        }
        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_WX_LOGIN,WXLoginResp::class.java)
                .subscribe(wxLogin)

        addRun(wxLogin)
    }

    fun startWechatLogin(){
        wxLoginLiveData.postValue(null)
        wxLoginReqSign = ShareHelper.login()
    }

    fun getClickEventLiveData():LiveData<Int> = clickEventLiveData

    fun getCaptcha(){
        addRun(Api.get().captcha.onResult(getCaptchaLiveData))
    }

    fun sendSMSVerify(phone: String,ticket:ValidatorResult){
        stepState!!.phone = phone
        val type = when(stepState.type){
            TYPE_LOGIN -> SMSType.SMS_TYPE_LOGIN
            TYPE_REG -> SMSType.SMS_TYPE_REG
            TYPE_FORGET_PWD -> SMSType.SMS_TYPE_RETRIEVE
            TYPE_WECHAT_BIND -> SMSType.SMS_TYPE_BIND
            else -> 0
        }
        if (type == 0){
            ToastUtils.showText("内部错误，请重启应用")
            return
        }
        if (SecurityCheckerUtils.canRequestCode()){
            addRun(Api.get().fetchPhoneVer(type,phone,ticket).onResult(smsCodeLiveData))
        }else{
            smsCodeLiveData.postValue(Resource.error("获取验证码次数过多，请稍后重试！"))
            //addRun(Api.get().fetchPhoneVer(type,phone,ticket).onResult(smsCodeLiveData))
        }

    }

    fun doLogin(phone:String,pwd:String,fromPwd:Boolean){
        if (fromPwd){
            //账号密码登录
            addRun(Api.get().fetchLoginAcc(phone,pwd).onResult(userLoginLiveData))
        }else{
            //验证码登录
            addRun(Api.get().fetchLoginPhone(phone,pwd).onResult(userLoginLiveData))
        }

    }

    fun doLogin(token:String?){
        addRun(Api.get().fetchOneKeyLogin(token).onResult(userLoginLiveData))
    }

    fun setUserLogined(userMode: UserMode){
        DataCenter.get().saveUserMode(userMode)
        userModeLiveData.postValue(userMode)
        ScTimes.addLogin()
    }

    fun getWXLoginLiveData():LiveData<WXLoginResp?> = wxLoginLiveData

    fun getUserLoginLiveData():LiveData<Resource<UserMode?>> = userLoginLiveData

    fun getUserModeLiveData():LiveData<UserMode?> = userModeLiveData

    fun getSMSCodeLiveData():LiveData<Resource<Boolean?>> = smsCodeLiveData

    fun getCaptchaLiveData():LiveData<Resource<CaptchaData?>> = getCaptchaLiveData

    fun resetSMSCode(){
        smsCodeLiveData.value = null
    }
}